package cn.bfay.lion.jingdong.client;

import feign.FeignException;
import feign.Request;
import feign.Response;
import feign.Retryer;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * JdProductClientConfiguration.
 *
 * @author wangjiannan
 */
public class JdProductClientConfiguration {
    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Request.Options feignOptions() {
        return new Request.Options(2000, 5000);
    }

    @Bean
    public Retryer feignRetryer() {
        return new Retryer.Default(1000, 5000, 2);
    }

    @Bean
    public feign.codec.Decoder productDecoder() {
        return new ResponseEntityDecoder(new ProductDecoder(messageConverters));
    }

    private static class ProductDecoder extends SpringDecoder {
        public ProductDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
            super(messageConverters);
        }

        @Override
        public Object decode(Response response, Type type) throws IOException, FeignException {
            String content = (String) super.decode(response, String.class);
            return StringUtils.trimAllWhitespace(content);
        }
    }
}
